package coupon

import (
	// "bp/cache"
	"bp/conf"
	"bp/db"

	// "bgs/grpc/client"
	internalHttpMiddleware "bp/internal/middleware/http"
	"bp/internal/service/entity"
	"bp/internal/twirpex"
	"go.uber.org/zap"

	// "bp/internal/util"
	messageGrpc "bp/rpc/gen/shared/message"
	couponGrpc "bp/rpc/gen/webapi/coupon"
	"context"

	"github.com/go-chi/chi"
	"github.com/golang/protobuf/ptypes/empty"
)

type CouponWebApiImp struct {
	dao       *db.PgDao
	slog      *zap.SugaredLogger
	vars      *conf.VarsSection
	entityHub *entity.EntityHub
	// cacher *cache.Adapter
	// couponGrpc.CouponOpServiceServer
	couponGrpc.CouponOpService
}

// NewCouponWebApi initialization
func NewCouponWebApi(
	slog *zap.SugaredLogger,
	pgdao *db.PgDao,
	vars *conf.VarsSection,
	entityHub *entity.EntityHub,
	// adp *cache.Adapter,
) (ws *CouponWebApiImp) {
	ws = &CouponWebApiImp{
		dao:       pgdao,
		slog:      slog.With("module", "CouponWebApi"),
		vars:      vars,
		entityHub: entityHub,
		// cacher:           adp,
	}
	return
}

const (
	EntityName                    string = "优惠券"
	PingCouponMethod              string = "/coupon/ping/exec"
	CreateCouponMethod            string = "/coupon"                     // POST
	UpdateCouponMethod            string = "/coupon"                     // PUT
	PublishCouponMethod           string = "/coupon/{id}/publish"        // PUT
	PauseCouponMethod             string = "/coupon/{id}/pause"          // PUT
	ResumeCouponMethod            string = "/coupon/{id}/resume"         // PUT
	GetCouponMethod               string = "/coupon/{id}"                // GET
	ListCouponsMethod             string = "/coupons"                    // GET
	ListCouponWithStatsMethod     string = "/couponWithStats"            // GET
)

// RegisterToWeb 将部分grpc方法注册到web
func (s *CouponWebApiImp) RegisterToWeb(r chi.Router) {
	couponRT := twirpex.NewSingleTwirpServerProxy(couponGrpc.NewCouponOpServiceServer(s))

	r.Group(func(r chi.Router) {
		r.Get(PingCouponMethod, couponRT.Handle("PingCoupon"))
		r.Group(func(r chi.Router) {
			r.Use(internalHttpMiddleware.WithBilinToken(s.slog, s.vars))
			r.Post(CreateCouponMethod, couponRT.Handle("CreateCoupon"))
			r.Put(UpdateCouponMethod, couponRT.Handle("UpdateCoupon"))
			r.Put(PublishCouponMethod, couponRT.Handle("PublishCoupon"))
			r.Put(PauseCouponMethod, couponRT.Handle("PauseCoupon"))
			r.Put(ResumeCouponMethod, couponRT.Handle("ResumeCoupon"))
			r.Get(GetCouponMethod, couponRT.Handle("GetCoupon"))
			r.Group(func(r chi.Router) {
				r.Use(internalHttpMiddleware.WithPager(s.slog, s.vars))
				r.Get(ListCouponsMethod, couponRT.Handle("ListCoupons"))
				r.Get(ListCouponWithStatsMethod, couponRT.Handle("ListCouponWithStats"))
			})
		})
	})
}

func (s *CouponWebApiImp) PingCoupon(ctx context.Context, _ *empty.Empty) (res *messageGrpc.PingRes, err error) {
	res = &messageGrpc.PingRes{
		Msg: "ok",
	}
	return
}
